<template>
  <div class="register_page">
    <Logo />
    <div class="content">
      <div class="content_left">
        <div class="title">欢迎使用互盛科技产融数字服务平台</div>
        <div class="describtion">
          为核心企业、供应链上下游企业及金融机构建立良好的沟通渠道，促使多方互信、合作、共赢
        </div>
        <img src="@/assets/register/welcome.png" alt="" class="welcome_img" />
      </div>
      <div class="content_right">
        <el-form
          ref="registerForm"
          :model="registerForm"
          :rules="registerRules"
          class="register_form"
        >
          <h3 class="title">账号注册</h3>
          <el-form-item prop="phonenumber">
            <el-input
              v-model="registerForm.phonenumber"
              type="text"
              auto-complete="off"
              placeholder="请输入管理员手机号"
              :clearable="true"
            >
              <i slot="prefix" class="el-icon-mobile-phone"></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              auto-complete="off"
              placeholder="请输入登录密码"
              :clearable="true"
              @keyup.enter.native="handleRegister"
            >
              <i slot="prefix" class="el-icon-lock" />
            </el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              auto-complete="off"
              placeholder="请再次输入登录密码"
              :clearable="true"
              @keyup.enter.native="handleRegister"
            >
              <i slot="prefix" class="el-icon-lock" />
            </el-input>
          </el-form-item>
          <el-form-item prop="code" class="code_line">
            <el-input
              v-model="registerForm.code"
              auto-complete="off"
              placeholder="请输入短信验证码"
              @keyup.enter.native="handleRegister"
            >
              <i slot="prefix" class="el-icon-mobile-phone"></i>
            </el-input>
            <el-button
              type="text"
              class="get_code"
              :loading="codeLoading"
              @click="getCode"
            >{{ sNumber > -1 ? sNumber + 's' : '获取验证码' }}</el-button>
          </el-form-item>
          <el-form-item prop="agreement" class="agree_line">
            <el-checkbox v-model="registerForm.agreement"></el-checkbox>
            <span class="agree_txt">我已阅读并同意</span>
            <a
              class="agreement agreement_1"
              :href="baseURL + downloadTemplate3.fileUrl"
              target="_blank"
            >《互盛科技平台服务协议》、</a>
            <a
              class="agreement agreement_2"
              :href="baseURL + downloadTemplate5.fileUrl"
              target="_blank"
            >《平台用户隐私政策》</a>
          </el-form-item>
          <el-form-item style="width: 100%; margin-bottom: 0">
            <el-button
              :loading="loading"
              size="medium"
              type="primary"
              class="submit_btn"
              @click.native.prevent="handleRegister"
            >
              <span v-if="!loading">注 册</span>
              <span v-else>注 册 中...</span>
            </el-button>
          </el-form-item>
          <div class="info_text">
            <el-icon :style="{ color: themeColor }" class="el-icon-info" />
            提交注册请求后，您可以以临时身份访问系统，需进行相关认证流程才能享受其他服务操作
          </div>
          <div class="change_login">
            已有账号？
            <el-button type="text" style="padding: 0;" @click="goToLogin">去登录</el-button>
          </div>
        </el-form>
      </div>
    </div>
    <Copyright />
  </div>
</template>

<script>
import { getCode, register } from "@/api/login";
import Logo from "@/customComponents/logo";
import Copyright from '@/customComponents/copyright';
import colors from "@/assets/styles/variables.scss";
import { downloadTemplate } from "@/api/authenticate";
import { setToken } from '@/utils/auth'

export default {
  name: "Register",
  components: {
    Logo,
    Copyright,
  },
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      baseURL: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API :
        process.env.VUE_APP_HTTP_REQUEST_ADDRESS,
      themeColor: colors.themeColor,
      registerForm: {
        phonenumber: "",
        password: "",
        confirmPassword: "",
        code: "",
        uuid: "",
        agreement: false,
      },
      registerRules: {
        phonenumber: [
          { required: true, trigger: ["change", 'blur'], message: "请输入管理员手机号" },
          {
            validator: (rule, value, callback) => {
              console.log(value)
              if (/^1\d{10}/.test(value)) {
                callback()
              } else {
                callback('请输入正确手机号')
              }
            },
            trigger: ["change", 'blur'],
          },
        ],
        password: [
          { required: true, trigger: ["change", 'blur'], message: "请输入您的密码" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: ["change", 'blur'],
          },
          {
            pattern: /^[^<>"'|\\]+$/,
            message: "不能包含非法字符：< > \" ' \\\ |",
            trigger: ["change", 'blur'],
          },
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请输入密码'));
              } else {
                if (this.registerForm.confirmPassword !== '') {
                  this.$refs.registerForm.validateField('confirmPassword');
                }
                callback();
              }
            },
            trigger: ["change", 'blur']
          }
        ],
        confirmPassword: [
          { required: true, trigger: ['change', 'blur'], message: "请再次输入您的密码" },
          { required: true, validator: equalToPassword, trigger: ['change', 'blur'] },
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请再次输入密码'));
              } else if (value !== this.registerForm.password) {
                callback(new Error('两次输入密码不一致!'));
              } else {
                callback();
              }
            },
            trigger: ['change', 'blur']
          }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
        agreement: [{ validator: (rule, value, callback) => {
          if (value) {
            callback()
          } else {
            callback('请勾选协议')
          }
        }, trigger: ['change', 'blur'] }]
      },
      loading: false,
      downloadTemplate3: {
        fileUrl: '',
        fileType: '',
        agreementName: '',
      },
      downloadTemplate5: {
        fileUrl: '',
        fileType: '',
        agreementName: '',
      },
      codeLoading: false,
      sNumber: -1, // 倒计时
      timer: null, // 倒计时
    };
  },
  mounted() {
    this.downloadTemplate(3).then((res) => {
      this.downloadTemplate3 = res.data;
    }); // 互盛科技平台服务注册协议
    this.downloadTemplate(5).then((res) => {
      this.downloadTemplate5 = res.data;
    }); // 平台用户隐私协议
  },
  methods: {
    // 下载模板
    downloadTemplate(id) {
      return new Promise((resolve, reject) => {
        downloadTemplate(id).then((res) => {
          resolve(res);
        });
      });
    },
    countFn() {
      this.timer = setTimeout(() => {
        if (this.sNumber > -1) {
          --this.sNumber
          this.countFn()
        } else {
          clearTimeout(this.timer)
          this.timer = null
        }
      }, 1000);
    },
    countDown() {
      this.sNumber = 60
      this.countFn()
    },
    getCode() {
      this.$refs.registerForm.validateField(['phonenumber'], (valid) => {
        if (!valid) {
          this.codeLoading = true
          getCode({ phonenumber:  this.registerForm.phonenumber }, 0).then((res) => {
            this.codeLoading = false
            this.registerForm.uuid = res.uuid;
            this.countDown()
          }).catch(() => {
            this.codeLoading = false
          })
        }
      })
    },
    handleRegister() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          register({
            phonenumber: this.registerForm.phonenumber,
            password: this.registerForm.password,
            // confirmPassword: "",
            code: this.registerForm.code,
            uuid: this.registerForm.uuid,
            inviteCode: this.$route.query?.inviteCode || '',
          })
            .then((res) => {
              const phonenumber = this.registerForm.phonenumber;
              this.$alert(
                "<font color='red'>恭喜你，您的账号 " +
                  phonenumber +
                  " 注册成功！</font>",
                "系统提示",
                {
                  dangerouslyUseHTMLString: true,
                  type: "success",
                }
              )
                .then(() => {
                  setToken(res.token)
                  this.$router.push({
                    path: "/registerSuccess"
                  });
                })
                .catch(() => {});
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
    goToLogin() {
      this.$router.push({
        path: '/login'
      })
    }
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/styles/px2rem.scss';
@import "@/assets/styles/variables.scss";

.register_page {
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .content {
    display: flex;
    justify-content: center;
    .content_left {
      margin-right: px2rem(118);
      .title {
        color: $theme;
        font-size: px2rem(40);
        font-weight: 600;
        height: px2rem(56);
        line-height: px2rem(56);
        margin-bottom: px2rem(12);
        text-align: center;
      }
      .describtion {
        color: #516ea3;
        font-size: px2rem(18);
        height: px2rem(52);
        line-height: px2rem(26);
        text-align: center;
        // width: px2rem(584);
        margin: 0 auto px2rem(34);
      }
      .welcome_img {
        display: block;
        width: px2rem(584);
        height: px2rem(545);
        margin: 0 auto;
      }
    }
    .content_right {
      display: flex;
      align-items: flex-start;
      .register_form {
        margin-top: px2rem(56);
        border-radius: px2rem(20);
        background: #ffffff;
        width: 520px;
        padding: px2rem(48) px2rem(48) px2rem(40);
        box-shadow: rgba(0, 88, 255, 0.4) px2rem(5) px2rem(6) px2rem(14) 0;
        .title {
          margin: px2rem(0) auto px2rem(30) auto;
          color: $theme;
          font-size: px2rem(32);
          font-weight: 600;
        }
        .input-icon {
          height: px2rem(39);
          width: px2rem(14);
          margin-left: px2rem(2);
        }
        .register-tip {
          font-size: 13px;
          text-align: center;
          color: #bfbfbf;
        }
        .code_line {
          position: relative;
          .get_code {
            position: absolute;
            top: 0;
            bottom: 0;
            right: px2rem(14);
            z-index: 2;
            font-size: 14px;
          }
        }
        .register-code {
          width: 33%;
          height: px2rem(38);
          float: right;
          img {
            cursor: pointer;
            vertical-align: middle;
          }
        }
        .agree_line {
          font-size: 14px;
          margin-bottom: 22px;
          ::v-deep .el-form-item__content {
            line-height: px2rem(20);
          }
          .agree_txt {
            color: #999;
            margin-left: px2rem(6);
          }
          .agreement {
            color: $theme;
          }
        }
      }
      .info_text {
        color: #999;
        font-size: 14px;
        line-height: px2rem(20);
        margin-top: px2rem(12);
      }
      .change_login {
        text-align: center;
        color: #999;
        font-size: 12px;
        margin-top: px2rem(20);
      }
      .submit_btn {
        width: 100%;
        background: linear-gradient(90deg, #0058ff 0%, #69adff 100%);
        border: none;
        height: px2rem(48);
        font-weight: 600;
        font-size: 18px;
        padding-top: 0;
        padding-bottom: 0;
      }
    }
  }
}
</style>
